export async function syncDiyField(sourceConn, targetConn, diyTable) {
  const tableId = diyTable.Id;

  // 查询源库字段
  const [sourceFields] = await sourceConn.query(`SELECT * FROM diy_field WHERE TableId = ?`, [tableId]);
  if (sourceFields.length === 0) {
    console.log(`⚠️ 源库 diy_field 无数据(TableId=${tableId})`);
    return [];
  }

  // 查询目标库字段
  const [targetFields] = await targetConn.query(`SELECT * FROM diy_field WHERE TableId = ?`, [tableId]);

  if (targetFields.length > 0) {
    // 删除目标库旧字段
    await targetConn.query(`DELETE FROM diy_field WHERE TableId = ?`, [tableId]);
    console.log(`🗑️ 已清空目标库 diy_field(TableId=${tableId})`);
  }

  // 1. 补齐目标库 diy_field 缺失字段
  const [srcCols] = await sourceConn.query('SHOW COLUMNS FROM diy_field');
  const [tgtCols] = await targetConn.query('SHOW COLUMNS FROM diy_field');
  const tgtColNames = tgtCols.map(col => col.Field);
  for (const srcCol of srcCols) {
    if (!tgtColNames.includes(srcCol.Field)) {
      const addSql = `ALTER TABLE diy_field ADD COLUMN \`${srcCol.Field}\` ${srcCol.Type} ${srcCol.Null === "NO" ? "NOT NULL" : ""} ${srcCol.Default !== null ? `DEFAULT '${srcCol.Default}'` : ""}`;
      await targetConn.query(addSql);
      console.log(`➕ [syncDiyField] 补充目标库 diy_field 字段: ${srcCol.Field}`);
    }
  }

  // 插入源库字段
  const fieldKeys = Object.keys(sourceFields[0]);
  const placeholders = fieldKeys.map(() => "?").join(", ");
  const escapedKeys = fieldKeys.map((k) => `\`${k}\``).join(", ");
  const insertSql = `INSERT INTO diy_field (${escapedKeys}) VALUES (${placeholders})`;

  const insertPromises = sourceFields.map((field) => {
    const values = fieldKeys.map((k) => field[k]);
    return targetConn.query(insertSql, values);
  });

  await Promise.all(insertPromises);
  console.log(`✅ 同步 ${sourceFields.length} 条 diy_field 记录`);

  return sourceFields;
}
